package com.example.my0612zuoye;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;

import android.content.ContentValues;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity {
    ListView listView;
    MyListAdpater adpater;
    List<Phone.DataBean.PhonesBean>list;
    Mysql mysql;
    Phone phone;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        listView=findViewById(R.id.listview);
        mysql=new Mysql(this);

        try {
            Gson gson=new Gson();
            StringBuilder builder=new StringBuilder();
            AssetManager assets = getAssets();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(assets.open("phonedata.json")));
            String line;
            while((line=bufferedReader.readLine())!=null){
                builder.append(line);
                Log.e( "onCreate: ",line );
            }
            phone = gson.fromJson(builder.toString(), Phone.class);
            Log.e( "onCreate: ",phone.getData().getPhones().get(0).getName()+"----------------");

        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e( "onCreate: ",phone.getData().getPhones().get(1).getName()+"----------------");
        sql();
        list=phone.getData().getPhones();
        adpater=new MyListAdpater(list,this);
        listView.setAdapter(adpater);

    }
    void sql(){
        SQLiteDatabase db=mysql.getWritableDatabase();
        for (int i=0;i<phone.getData().getPhones().size();i++) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("name",phone.getData().getPhones().get(i).getName());
            contentValues.put("price",phone.getData().getPhones().get(i).getPrice());
            contentValues.put("brand",phone.getData().getPhones().get(i).getBrand());
            db.insert("phone",null,contentValues);
        }
        db.close();
    }
}
